<?php
class AskController extends FrontendController
{
	public function actions()
	{
		return array(
				// captcha action renders the CAPTCHA image displayed on the contact page
				'captcha'=>array(
						'class'=>'CCaptchaAction',
						'backColor'=>0xFFFFFF,
				),
		);
	}
	public function actionSend()
	{
		$model = new FrontendAskModel;
		$askForm = new AskForm;
		if(isset($_POST['AskForm'])){
			$askForm->attributes = $_POST['AskForm'];
			if($askForm->save()){
				Yii::app()->user->setFlash('reply-flash','Câu hỏi của bạn đã gửi thành công.');
				$returnUrl = Yii::app()->createUrl('/default/page', array('alias'=>'hoi-dap'));
				$this->redirect($returnUrl);
			}
		}
		$this->render('send', array(
				'askForm'=>$askForm				
		));
	}
	public function actionIndex()
	{
		//
	}
	public function actionDetail()
	{
		$id = Yii::app()->request->getParam('id',0);
		$model = new FrontendAnswersModel;
		$answerForm = new AnswerForm;
		$this->performAjaxValidation($answerForm);
		if(isset($_POST['AnswerForm'])){
			$answerForm->attributes = $_POST['AnswerForm'];
			if($answerForm->save()){
				Yii::app()->user->setFlash('reply-flash','Cảm ơn bạn đã góp ý kiến.');
				$urlReturn = $this->createUrlAskDetail($id);
				$this->redirect($urlReturn);
			}
		}
		$askDetail = FrontendAskModel::model()->findByPk($id);
		
		$totalAnswer = FrontendAnswersModel::model()->getTotalAnswerByAsk($id);
		if($totalAnswer>0){
			$paging = new CPagination($totalAnswer);
			$itemOnPaging = 5;
			$paging->pageSize = Yii::app()->params['aa_perpage'];
			$curr_page = $paging->getCurrentPage();
			
			$answerList = FrontendAnswersModel::model()->getAnswerByAsk($id, $paging->getLimit(), $paging->getOffset());
			$this->render('detail', array(
					'askDetail'=>$askDetail,
					'paging'=>$paging,
					'totalAnswer'=>$totalAnswer,
					'answerList'=>$answerList,
					'itemOnPaging'=>$itemOnPaging,
					'answerForm'=>$answerForm,
					'ask_id'=>$id
			));
		}else
		$this->render('detail', array(
					'askDetail'=>$askDetail,
					'answerForm'=>$answerForm,
					'totalAnswer'=>$totalAnswer,
					'ask_id'=>$id
				));
	}
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='aa-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}